package com.wedistudio.scribd.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.wedistudio.android.framework.fetcher.URLParams;
import com.wedistudio.android.framework.service.Service;
import com.wedistudio.android.framework.service.ServiceException;
import com.wedistudio.android.framework.service.ServiceRequestConverter;
import com.wedistudio.android.framework.service.ServiceResponseConverter;
import com.wedistudio.scribd.ScribdUtils;
import com.wedistudio.scribd.xml.RSP;
import com.wedistudio.slidesprovider.Language;
import com.wedistudio.slidesprovider.SearchCriteria;
import com.wedistudio.slidesprovider.Slide;
import com.wedistudio.slidesprovider.Slides;

public class GetSlidesFromCriteria extends Service<SearchCriteria, Slides> {

	private static String ACTION = "docs.search";

	public static GetSlidesFromCriteria create() {
		return new GetSlidesFromCriteria();
	}

	private String lang(Language language) {
		switch (language) {
		case ANY:
			return "";
		case ARABIC:
			return "ar";
		case CHINESE:
			return "zh";
		case DUTCH:
			return "nl";
		case ENGLISH:
			return "en";
		case FRENCH:
			return "fr";
		case GERMAN:
			return "de";
		case ITALIAN:
			return "it";
		case JAPANESE:
			return "ja";
		case KOREAN:
			return "ko";
		case PORTUGUESE:
			return "pt";
		case ROMANIAN:
			return "ro";
		case SPANISH:
			return "es";
		default:
			break;
		}

		return "";
	}

	private GetSlidesFromCriteria() {
		setRequestConverter(new ServiceRequestConverter<SearchCriteria>() {

			@Override
			public List<URLParams> convert(SearchCriteria request)
					throws ServiceException {
				List<URLParams> result = new ArrayList<URLParams>();
				URLParams params = ScribdUtils.buildURLParams(ACTION);
				params.addParam("query", request.getKeyword());
				String lang = lang(request.getLanguage());
				if (lang.length() > 0)
					params.addParam("language", lang);
				params.addParam("num_start", "" + request.getOffset());
				params.addParam("num_results", "" + request.getLimit());
				result.add(params);
				return result;
			}
		});

		setResponseConverter(new ServiceResponseConverter<Slides>() {

			@Override
			public Slides convert(Map<URLParams, String> raw)
					throws ServiceException {
				String xml = null;
				for (Map.Entry<URLParams, String> entry : raw.entrySet()) {
					xml = entry.getValue();
				}
				RSP rsp = ScribdUtils.getResponse(xml);

				Slides result = new Slides("",
						rsp.resultset.totalResultsAvailable,
						rsp.resultset.firstResultPosition);

				for (final RSP.ResultSet.Result item : rsp.resultset.results) {
					Slide slide = item.getSlide();
					result.add(slide);
				}
				return result;
			}
		});
	}
}
